Java For Complete Beginners: Step By Step with Full Explanation for Java Beginners by Abdelmoniem Mohammed
Author:Abdelmoniem, Mohammed [Abdelmoniem, Mohammed]
Language: eng
Format: epub
Publisher: Mohammed Abdelmoniem
Published: 2020-09-11T00:00:00+00:00
2nd Override the compareTo() method of Comparable interface. The compareTo() method is used to compare the current object with the specified object.
Letâs say we need to sort the ArrayList<Book> based on year of publication property â first implement Comparable interface and then Override the compareTo method, as shown in the Book2.java file.
Example 14.16 : Book2.java
01 package ch14;
02
03 public class Book2 implements Comparable<Book2>{
04 private String bookName;
05 private int pageNo;
06 private int pubYear;
07
08 public Book2(String bookName, int pageNo, int pubYear){
09 this.bookName = bookName;
10 this.pageNo = pageNo;
11 this.pubYear = pubYear;
12 }
13 public String getBookName(){
14 return bookName;
15 }
16 public void setBookName(String bookName){
17 this.bookName = bookName;
18 }
19 public int getPageNo(){
20 return pageNo;
21 }
22 public void setPageNo(int pageNo){
23 this.pageNo = pageNo;
24 }
25 public int getPubYear(){
26 return pubYear;
27 }
28 public void setPubYear(int pubYear){
29 this.pubYear = pubYear;
30 }
31
32 @Override
33 public String toString(){
34 return ("Book Name = " + bookName + ", Page No = " +
35 pageNo + ", Publish Year = " + pubYear);
36 }
37 @Override
38 public int compareTo(Book2 compareto){
39 int comparepub;
40 comparepub = compareto.getPubYear();
41
42 // For Ascending order
43 return this.pubYear - comparepub;
44 }
45 }
Now we can very well call Collections.sort on ArrayList.
Example 14.17 : BookDemo2.java
01 package ch14;
02
03 import java.util.*;
04
05 public class BookDemo2 {
06 public static void main(String[] args) {
07 ArrayList<Book2> list = new ArrayList<Book2>();
08 list.add(new Book2("C Programming", 552, 2007));
09 list.add(new Book2("How to Design Classes", 666, 2012));
10 list.add(new Book2("Modern C", 222, 2015));
11
12 Collections.sort(list);
13 for (Book2 str1: list) {
14 System.out.println(str1);
15 }
16 }
17 }
Output
Book Name = C Programming, Page No = 552, Publish Year = 2007
Book Name = How to Design Classes, Page No = 666, Publish Year = 2012
Book Name = Modern C, Page No = 222, Publish Year = 2015
As you can see that Book2 array is sorted by publication year in ascending order. If we want sort books by name, we have to change Book2 class to do that:
Example 14.18 : Book2.java (revised version)
01 package ch14;
02
03 public class Book2 implements Comparable<Book2>{
04 private String bookName;
05 private int pageNo;
06 private int pubYear;
07
08 public Book2(String bookName, int pageNo, int pubYear){
09 this.bookName = bookName;
10 this.pageNo = pageNo;
11 this.pubYear = pubYear;
12 }
13 public String getBookName(){
14 return bookName;
15 }
16 public void setBookName(String bookName){
17 this.bookName = bookName;
18 }
19 public int getPageNo(){
20 return pageNo;
21 }
22 public void setPageNo(int pageNo){
23 this.pageNo = pageNo;
24 }
25 public int getPubYear(){
26 return pubYear;
27 }
28 public void setPubYear(int pubYear){
29 this.pubYear = pubYear;
30 }
31
32 @Override
33 public String toString(){
34 return ("Book Name = " + bookName + ", Page No = " +
35 pageNo + ", Publication Year = " + pubYear);
36 }
37 /* @Override
38 // Comparison by publication year
39 public int compareTo(Book2 compareto){
40 int comparepub;
41 comparepub = compareto.getPubYear();
42
43 // For Ascending order
44 return this.pubYear-comparepub;
45 }*/
46
47 @Override
48 // Comparison by name
49 public int compareTo(Book2 compareto){
50 int comparepub;
51 comparepub = compareto.getBookName().compareTo(getBookName());
52 return comparepub;
53 }
54 }
Example 14.19 : DemoBook2.java (revised version)
01 package ch14;
02
03 import java.util.*;
04
05 public class BookDemo2 {
06 public static void main(String[] args) {
07 ArrayList<Book2> list = new ArrayList<Book2>();
08 list.add(new Book2("C Programming", 552, 2007));
09 list.add(new Book2("How to Design Classes", 666, 2012));
10 list.add(new Book2("Modern C", 222, 2015));
11
12 // For Descending order
13 Collections.sort(list);
14 for (Book2 str1: list) {
15 System.
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Personalized inhaled bacteriophage therapy for treatment of multidrug-resistant Pseudomonas aeruginosa in cystic fibrosis by unknow(208566)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(102475)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(102011)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(101802)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74594)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50985)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(40363)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(40284)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(40187)
Alkaline-earth metals promote propane dehydrogenation with carbon dioxide through geometric effects: Altering the reaction pathway by unknow(32806)
Induced iron vacancies boosting FeOOH loaded on sustainable Fenton-like collagen fiber membrane for efficient removal of emerging contaminants by unknow(32602)
Efficient electric-field-assisted photochemical conversion of methane to n-propanol exclusively over penetrated TiO2Ti hollow fibers by Guanghui Feng(32520)
Bi2SiO5 nanosheets as piezo-photocatalyst for efficient degradation of 2,4-Dichlorophenol by Hangyu Shi & Yifu Li & Lishan Zhang & Guoguan Liu & Qian Zhang & Xuan Ru & Shan Zhong(32458)
A novel NDIPTA organic heterojunction photocatalyst with built-in electric field for efficient hydrogen production by Jiahui Yang & Baojun Ma & Yongfa Zhu(32432)
Enhanced conversion of methane to liquid-phase oxygenates via hollow ferrite nanotube@horseradish peroxidase based photoenzymatic catalysis by Jun Duan & Shiying Fan & Xinyong Li & Shaomin Liu(32397)
Ordered macroporous superstructure of defective carbon adorned with tiny cobalt sulfide for selective electrocatalytic hydrogenation of cinnamaldehyde by Xiao-Shi Yuan & Sheng-Hua Zhou & San-Mei Wang & Wenbo Wei & Xiaofang Li & Xin-Tao Wu & Qi-Long Zhu(32321)
What's Done in Darkness by Kayla Perrin(27235)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26617)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26545)